'use strict';
const request = require('request');
const Controller = require('egg').Controller;

class UserController extends Controller {
    // 注册
    async reg() {
        let { ctx, app } = this;
        // 参数验证
        ctx.validate({
            username: {
                type: 'string',
                required: true,
                range: {
                    min: 2,
                    max: 20
                },
                desc: '用户名'
            },
            password: {
                type: 'string',
                required: true,
                desc: '密码'
            },
            repassword: {
                type: 'string',
                required: true,
                desc: '确认密码'
            },
            class_id: {
                type: 'int',
                required: true,
                desc: '班级'
            }
        }, {
            equals: [
                ['password', 'repassword']
            ]
        });
        let { username, password, class_id } = ctx.request.body;
        let openid = await this.service.cache.get('openid');
        // 验证用户是否已经存在
        if (await app.model.User.findOne({
            where: {
                username,
            }
        })) {
            ctx.throw(400, '用户名已存在');
        }
        // 创建用户
        let user = await app.model.User.create({
            username,
            password,
            openid,
            class_id,
        });
        if (!user) {
            ctx.throw(400, '创建用户失败');
        }
        ctx.apiSuccess(user);
    }

    // 登录
    async login() {
        const { ctx, app } = this;
        // 参数验证
        ctx.validate({
            username: {
                type: 'string',
                required: true,
                desc: '用户名'
            },
            password: {
                type: 'string',
                required: true,
                desc: '密码'
            },
        });
        let { username, password } = ctx.request.body;
        // 验证该用户是否存在|验证该用户状态是否启用
        let user = await app.model.User.findOne({
            include: [
                {
                    model: app.model.Class,
                }],
            where: {
                username,
            }
        });
        if (!user) {
            ctx.throw(400, '用户不存在或已被禁用');
        }
        // 验证密码
        await ctx.checkPassword(password, user.password);

        user = JSON.parse(JSON.stringify(user));
        // 生成token
        let token = ctx.getToken(user);
        user.token = token;
        delete user.password;
        // 加入缓存中
        if (!await this.service.cache.set('user_' + user.id, token)) {
            ctx.throw(400, '登录失败');
        }
        // 返回用户信息和token
        return ctx.apiSuccess(user);
    }

    // 退出登录
    async logout() {
        const { ctx, service } = this
        let current_user_id = ctx.authUser.id

        if (!(await service.cache.remove('user_' + current_user_id))) {
            ctx.throw(400, '退出登录失败')
        }

        ctx.apiSuccess('ok')
    }

    // 获取当前用户信息
    async info() {
        const { ctx } = this
        let user = JSON.parse(JSON.stringify(ctx.authUser))
        delete user.password
        ctx.apiSuccess(user)
    }

    // 获取当前用户openId
    async openid() {
        const { ctx, app } = this;
        let { code } = ctx.request.body;
        const urlStr = 'https://api.weixin.qq.com/sns/jscode2session'
        const data = {
            appid: this.config.mp.appid,           // 小程序 appId
            secret: this.config.mp.appSecret,      // 小程序 appSecret
            js_code: code,         // 登录时获取的 code
            grant_type: 'authorization_code' // 授权类型，此处只需填写 authorization_code
        }
        const result = await ctx.curl(urlStr, {
            data: data,
            dataType: 'json',
        });
        console.log(result)
        if (result.status != 200) {
            // ctx.body = {
            //     status: 101,
            //     msg: '操作失败',
            //     errcode: result.data.errcode,
            //     errmsg: result.data.errmsg
            // };
            ctx.apiFail(result.data)

        } else {
            // ctx.body = {
            //     status: 100,
            //     msg: '操作成功',
            //     openid: result.data.openid,
            //     session_key: result.data.session_key
            // };
            await this.service.cache.set('openid', result.data.openid)
            await this.service.cache.set('sessionkey', result.data.session_key)
            ctx.apiSuccess(result.data)
        }
    }
}

module.exports = UserController;
